package drds.data_propagate.parse;

import drds.data_propagate.parse.ha.HeartBeatCallback;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.TimerTask;

class HeartBeatTimeTask extends TimerTask {

    private MysqlEventParser mysqlEventParser;
    private boolean reconnect = false;
    private DumperImpl dumper1;

    public HeartBeatTimeTask(MysqlEventParser mysqlEventParser, DumperImpl dumper1) {
        this.mysqlEventParser = mysqlEventParser;
        this.dumper1 = dumper1;
    }

    public void run() {
        try {
            if (reconnect) {
                reconnect = false;
                dumper1.reconnect();
            } else if (!dumper1.isConnected()) {
                dumper1.connect();
            }
            Long startTime = System.currentTimeMillis();

            // 可能心跳sql为select 1
            if (StringUtils.startsWithIgnoreCase(mysqlEventParser.heartBeatSql.trim(), "select")
                    || StringUtils.startsWithIgnoreCase(mysqlEventParser.heartBeatSql.trim(), "show")
                    || StringUtils.startsWithIgnoreCase(mysqlEventParser.heartBeatSql.trim(), "explain")
                    || StringUtils.startsWithIgnoreCase(mysqlEventParser.heartBeatSql.trim(), "desc")) {
                dumper1.query(mysqlEventParser.heartBeatSql);
            } else {
                dumper1.update(mysqlEventParser.heartBeatSql);
            }

            Long costTime = System.currentTimeMillis() - startTime;
            if (mysqlEventParser.haController != null && mysqlEventParser.haController instanceof HeartBeatCallback) {
                ((HeartBeatCallback) mysqlEventParser.haController).onSuccess(costTime);
            }
        } catch (SocketTimeoutException e) {
            if (mysqlEventParser.haController != null && mysqlEventParser.haController instanceof HeartBeatCallback) {
                ((HeartBeatCallback) mysqlEventParser.haController).onFailed(e);
            }
            reconnect = true;
            mysqlEventParser.log.warn("connect failed by ", e);
        } catch (IOException e) {
            if (mysqlEventParser.haController != null && mysqlEventParser.haController instanceof HeartBeatCallback) {
                ((HeartBeatCallback) mysqlEventParser.haController).onFailed(e);
            }
            reconnect = true;
            mysqlEventParser.log.warn("connect failed by ", e);
        } catch (Throwable e) {
            if (mysqlEventParser.haController != null && mysqlEventParser.haController instanceof HeartBeatCallback) {
                ((HeartBeatCallback) mysqlEventParser.haController).onFailed(e);
            }
            reconnect = true;
            mysqlEventParser.log.warn("connect failed by ", e);
        }

    }

    public DumperImpl getDumper1() {
        return dumper1;
    }
}
